from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import redis
from utils.encrypt import md5


class RegisterModelForm(forms.ModelForm):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3,5,7-9]\d{9}$', '手机号格式错误，请检查')])
    password = forms.CharField(label='密码', widget=forms.PasswordInput(render_value=True))
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(render_value=True))
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有插件，添加属性
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label, 'type': field.label}

    def clean_code(self):
        conn = redis.Redis(host='127.0.0.1', port=6379, encoding='utf-8')
        code = conn.get(self.cleaned_data.get('phone'))
        if self.clean_code != code:
            raise ValidationError('验证码已超时，请重新获取')
        return code

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    def clean_confirm_password(self):
        print(self.cleaned_data)
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        print(confirm)
        if confirm != pwd:
            raise ValidationError('两次输入密码不一致')
        return confirm


class LoginModelForm(forms.ModelForm):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3,5,7-9]\d{9}$', '手机号格式错误，请检查')])
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label, 'type': field.label}
